package com.wuyu.util;

/**
 * 雪花算法生成唯一ID
 * @author bingtangli
 * @date 2024/03/31
 */
public class SnowFlakeIdUtil {

    private static final long twepoch = 1288834974657L;
    private static final long workerIdBits = 10L;
    private static final long sequenceBits = 12L;
    private static final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    private static final long workerIdShift = sequenceBits;
    private static final long timestampLeftShift = sequenceBits + workerIdBits;
    private static final long sequenceMask = -1L ^ (-1L << sequenceBits);

    private static long workerId;
    private static long sequence = 0L;
    private static long lastTimestamp = -1L;

    public SnowFlakeIdUtil(long workerId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException("WorkerId must be between 0 and " + maxWorkerId);
        }
        this.workerId = workerId;
    }

    public static synchronized long nextId() {
        long timestamp = timeGen();

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("Clock moved backwards. Refusing to generate id");
        }

        if (timestamp == lastTimestamp) {
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }

        lastTimestamp = timestamp;

        return ((timestamp - twepoch) << timestampLeftShift)
                | (workerId << workerIdShift)
                | sequence;
    }

    private static long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    private static long timeGen() {
        return System.currentTimeMillis();
    }

}
